package socket.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import socketmessage.entity.Socketmessage;
import socketmessage.service.impl.Socketmessageserviceimpl;
import utils.RedisUtil;
import wxusersocket.service.impl.Wxusersocketserviceimpl;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Component
@EnableScheduling   // 2.开启定时任务
@ServerEndpoint("/websocket/send/{openid}")
public class WebSocketGroupService {


    private static Wxusersocketserviceimpl wxusersocketserviceimpl;

    private static Socketmessageserviceimpl socketmessageserviceimpl;

    private static RedisUtil redisUtil;

    private static Socketmessage socketmessage;

    @Autowired
    public void RedisUtil(RedisUtil redisUtil) {
        WebSocketGroupService.redisUtil = redisUtil;
    }

    @Autowired
    public void Wxusersocketserviceimpl(Wxusersocketserviceimpl wxusersocketserviceimpl) {
        WebSocketGroupService.wxusersocketserviceimpl = wxusersocketserviceimpl;
    }

    @Autowired
    public void Socketmessageserviceimpl(Socketmessageserviceimpl socketmessageserviceimpl) {
        WebSocketGroupService.socketmessageserviceimpl = socketmessageserviceimpl;
    }

    public WebSocketGroupService()
    {}

    private static ConcurrentHashMap<String, WebSocketGroupService> onlineUserMap = new ConcurrentHashMap<String, WebSocketGroupService>();
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static LinkedList<WebSocketGroupService> webSocketServiceList = new LinkedList<>();
    /**
     * concurrent包的线程安全Set，用来存放要发送的数据
     */
    private static LinkedList<String> messageList = new LinkedList<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;


    /**
     * 连接建立成功调用的方法
     */
    private String opendata;

    @OnOpen
    public void onOpen(Session session , @PathParam("openid") String openid) {
        this.session = session;
        webSocketServiceList.add(this);
        addOnlineCount();

        if (onlineUserMap.get(openid)==null)
        {
            onlineUserMap.put(openid,this);
        }

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("连接失败!!!!!!");
        }

        log.info("当前连接数为:" + onlineUserMap.size());
        log.info("当前连接人为:" + openid);

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("openid") String openid) {
        webSocketServiceList.remove(this);
        subOnlineCount();
        onlineUserMap.remove(this.opendata = openid);
        log.info("当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(Session session, @PathParam("openid") String openid, String message) throws IOException {
        JSONObject messagejson = JSONObject.parseObject(message);
        String openlast = openid+"#"+messagejson.getString("lastopenid");
        HashMap<String , Object> hashMap = new HashMap<>();
        hashMap.put("name",redisUtil.hmget(openlast).get("name"));
        hashMap.put("url",redisUtil.hmget(openlast).get("url"));
        hashMap.put("message",messagejson.getString("message"));
        hashMap.put("createtime",new Date());
        redisUtil.hmset(openlast,hashMap);
        log.info(String.valueOf(redisUtil.hmget(openlast)));

        if (onlineUserMap.get(messagejson.getString("lastopenid"))!=null)
        {
            Socketmessage socketmessage = new Socketmessage();
            socketmessage.setUsersocketid(openlast);
            socketmessage.setBeginmessage(messagejson.getString("message"));
            socketmessageserviceimpl.insertSelective(socketmessage);

            Msg msg = new Msg();
            msg.setType("userexist");
            msg.setOpenid(openid);
            msg.setMessage(message);

            onlineUserMap.get(messagejson.getString("lastopenid")).sendMessage(JSON.toJSONString(msg));
            log.info(openlast+":"+message);
        }else {
            onlineUserMap.put(messagejson.getString("lastopenid"),this);
            Msg msg = new Msg();
            msg.setType("useroff");
            msg.setOpenid(openid);
            msg.setMessage(message);
            onlineUserMap.get(messagejson.getString("lastopenid")).sendMessage(JSON.toJSONString(msg));
        }

        log.info("报文:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("错误原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    @ApiOperation("添加定时任务")
    @Scheduled(cron = "0/10 * * * * ?")
    private void scheduledSend() {
        try {
            //发送消息数
            for (String message : messageList) {
                //发送连接数
                for (WebSocketGroupService webSocketGroupService : webSocketServiceList) {
                    //发送消息
                    webSocketGroupService.sendMessage(message);
                }
            }
            if (!CollectionUtils.isEmpty(messageList)) {
                log.info("发送成功：共发送给[{}]个页面，[{}]个消息", webSocketServiceList.size(), messageList.size());
                messageList.clear();
            }
        } catch (Exception e) {
            log.error("发送失败：" + e);
            e.printStackTrace();
        }
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketGroupService.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketGroupService.onlineCount--;
    }


}
